var curType = 0;
var lev3Map = new Map();//资费类列出的所有3级数据
var selAllBusArr = [];//列出的所有3级数据
var selBusArr = [];//当前被选中的所有3级数据

/**
清除2级数据
**/
var cleanSecondData = function($busType){
  if(!$busType){
    $busType = $("#busType");
  }
  if(!$busType.hasClass("am-hide")){
    $busType.addClass("am-hide");
    $busType.empty();
  }
};
/**
清除3级数据
**/
var cleanThirdData = function($busName){
  if(!$busName){
    $busName = $("#busName");
  }
  if(!$busName.hasClass("am-hide")){
    $busName.addClass("am-hide");
    $busName.empty();
    $("#submit-btn").prop("disabled", true);
  }
};
/**
清除所有2、3级数据
**/
var cleanOldData = function(){
  cleanSecondData();
  cleanThirdData();
};
/**
置空内存数据
**/
var cleanOldArrData = function(){
  selAllBusArr = [];
  selBusArr = [];
};
/**
显示或隐藏已选模块名称区域
**/
var showOrHideSelModuleName = function(name){
  var moduleName = name;
  var $selModuleNameArea = $("#selModuleNameArea");
  var $selModuleName = $("#selModuleName");
  if(moduleName){
    $selModuleNameArea.removeClass("am-hide");
    $selModuleName.html(moduleName);
  }else{
    $selModuleNameArea.addClass("am-hide");
    $selModuleName.empty();
  }
};
/**
显示或隐藏已选业务类型名称区域
**/
var showOrHideSelBusTypeName = function(busTypeName){
  var $selBusTypeNameArea = $("#selBusTypeNameArea");
  var $selBusTypeName = $("#selBusTypeName");
  if(busTypeName){
    $selBusTypeNameArea.removeClass("am-hide");
    $selBusTypeName.html(busTypeName);
  }else{
    $selBusTypeNameArea.addClass("am-hide");
    $selBusTypeName.empty();
  }
};
/**
显示或隐藏已选业务名称区域
**/
var showOrHideSelBusName = function(busName){
  var $selBusNameArea = $("#selBusNameArea");
  var $selBusName = $("#selBusName");
  if(busName){
    $selBusNameArea.removeClass("am-hide");
    $selBusName.html(busName);
  }else{
    $selBusNameArea.addClass("am-hide");
    $selBusName.empty();
  }
};
/**
全选或者全不选事件处理
**/
var allCheck = function(){
  var $allCheckbox = $("input[name='ids']");
  var $submitBtn = $("#submit-btn");
  if($("#allCheck").is(":checked")) {
    $allCheckbox.prop("checked","true");
    $submitBtn.prop("disabled", false);
    var selAllBusArrLen = selAllBusArr.length;
    var selBusArrLen = selBusArr.length;
    selBusArr = [];
    if(selBusArrLen !== selAllBusArrLen){
      for(var i=0;i<selAllBusArrLen;i++){
        selBusArr.push(selAllBusArr[i]);
      }
    }
  }else{
    selBusArr = [];
    $allCheckbox.removeAttr("checked");
    $submitBtn.prop("disabled", true);
  }
  showBusinessNames();
};
/**
根据当前业务名称是否被选中动态显示在业务名称区域
**/
var showBusinessNames = function(){
  var len = selBusArr.length;
  var names = "";
  for(var i=0;i<len;i++){
    names += selBusArr[i].name;
    if(i !== (len-1)){
      names += "，";
    }
  }
  showOrHideSelBusName(names);
};
/**
绑定业务数据多选框点击事件
**/
var bindCheckboxEvent = function(){
  var $allCheckbox = $("input[name='ids']");
  $allCheckbox.each(function(){
    $(this).click(function(){
      var $thisObj = $(this);
      var busId = $thisObj.val();
      var busName = $thisObj.siblings("span").html();
      var $allCheck = $("#allCheck");
      var $submitBtn = $("#submit-btn");
      var selObj = {id:busId,name:busName};
      if($(this).is(":checked")){
        selBusArr.push(selObj);
        var selBusArrLen = selBusArr.length;
        if(selBusArr.length === selAllBusArr.length){
          $allCheck.prop("checked","true");
        }
        $submitBtn.prop("disabled", false);
      }else{
        selBusArr.remove(selObj);
        $allCheck.removeAttr("checked");
        if(selBusArr.length === 0){
          $submitBtn.prop("disabled", true);
        }
      }
      showBusinessNames();
    })
  });
};
/**
显示业务数据区域数据
**/
var showThirdDatas = function(busData,busTypeName){
  console.log("--showThirdDatas------");
  // console.log(typeof(busData));
  
  var $busName = $("#busName");
  cleanThirdData($busName);
  showOrHideSelBusTypeName(busTypeName);
  cleanOldArrData();
  
  var busDatas = busData;
  var children = lev3Map.get(busData);
  if(typeof(busData) === "number" && children){
    busDatas = JSON.parse(children);
  }

  // console.log(busData);

  if(busDatas){
     var len = busDatas.length;
     if(len > 0){
      $busName.removeClass("am-hide");
      var html = $("<div><input type=\"checkbox\" id=\"allCheck\" checked onclick=\"allCheck()\"/><span>(全部)</span></div>");
      $("#busName").append(html);
      var busNames = "";
      for(var i=0;i<len;i++){
        var bus = busDatas[i];
        console.log(len + " bus : " + bus);
        var html = $("<div><input type=\"checkbox\" name=\"ids\" checked value=\""+bus.id+"\"/><span>"+bus.name+"</span></div>");
        $("#busName").append(html);
        //业务名称数据存入数组
        selBusArr.push(bus);
        selAllBusArr.push(bus);
        busNames += bus.name;
        if(i !== (len-1)){
          busNames += "，";
        }
      }
      showOrHideSelBusName(busNames);
      bindCheckboxEvent();
      $("#submit-btn").prop("disabled", false);
    }else{
      alert("请配置业务数据！");
    }
  }else{
    alert("请配置业务数据！");
  }
};
/**
显示业务类型区域
**/
var showSecondDatas = function(busDatas){
  console.log("showSecondDatas");
  var $busType = $("#busType");
  cleanSecondData($busType);
  showOrHideSelBusName();
  showOrHideSelBusTypeName();

  if(busDatas){
     var len = busDatas.length;
     if(len > 0){
      $busType.removeClass("am-hide");
      for(var i=0;i<len;i++){
        var bus = busDatas[i];
        // console.log(len + " bus : " + bus);
        var opthtml = $("<option class=\"am-text-sm\" onclick=\"showThirdDatas(" + bus.id + ",'" + bus.name + "')\">" + bus.name + "</option>");
        $("#busType").append(opthtml);
        if(bus.hasOwnProperty("children")){
          // console.log(bus.children);
          // 保存小类数据到map
          lev3Map.put(bus.id,bus.children);
        }
      }
    }else{
      alert("请配置业务数据！");
    }
  }else{
    alert("请配置业务数据！");
  }
};
/**
显示业务类型或者业务数据
**/
var showBusiness = function(busDatas){
  cleanOldData();
  cleanOldArrData();
  if(curType < 100){//资费类业务
    showSecondDatas(busDatas);
  }else{//非资费类业务
    showThirdDatas(busDatas);
  }
};

var loadBusiness = function(type){
  curType = type;
  var param = {
    actType : type
  };
  console.log(param);
  $.ajax({
    url : base + "/spreadMemberAuthConfig/loadBusiness",
    dataType : "json", 
    type : "post", 
    data : param,
    success : function(data){
      console.log(data);
      showBusiness(data);
    },
    error : function(msg) { // 若Ajax处理失败后回调函数，msg是返回的错误信息
      console.log(msg);
      alert("获取业务数据异常，请联系管理员！")
    }
  });
};

var getBusiness = function(type,name,remark){
  var moduleName = name;
  /*if(remark){
    moduleName += "（" + remark + "）";
  }*/
  showOrHideSelBusName();
  showOrHideSelBusTypeName();

  showOrHideSelModuleName(moduleName);

  loadBusiness(type);
};

var toBusinessList = function(){
  window.location.href = base + '/spreadMemberAuthConfig/businessList?list_select_type='+$("#busModule").val();
};

$(function() {
  console.log('------begin---------');
  $("#submit-btn").prop("disabled", true);
  $("#submit-btn").click(function(){
    var $submitBtn = $(this);
    var $allCheckbox = $("input[name='ids']:checked");
    var ids = $allCheckbox.serialize();
    var flowId = $("#flowId").val();
    var param = "config_business="+curType+"&"+ids+"&flowId="+flowId;
    console.log(param);
    $.ajax({
      url : base + '/spreadMemberAuthConfig/saveConfigData',
      data : param,
      dataType : "json",
      beforeSend : function(data) {
        $submitBtn.prop("disabled", true);
      },
      success : function(data) {
        $submitBtn.prop("disabled", false);
        if(data.status == "success") {
          if(confirm("提交成功，确定则立即跳到列表页面查看结果，取消则留在本页面继续配置，确定吗？")){
            // 跳转到列表页面
            toBusinessList();
          }
        }else{
          sendMessage({
            title : "提交失败！",
            text : data.message,
            type : data.status,
            timer : 2000,
            showConfirmButton : true
          });
        }
      }
    });
  });
});